﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace comtnet
{
    public class Client
    {
        private static byte[] result = new byte[1024 * 1024];
        static Socket ClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        private Thread read;

        private string net_ip = "";
        private int net_port = 0;

        public delegate void revDataDelegate(byte[] data);
        private revDataDelegate revdatadeal;

        public delegate void internetOnlineStatusDelegate(Boolean sta);
        public internetOnlineStatusDelegate netOnlineStatus;

        public Client(revDataDelegate callback)
        {
            revdatadeal = new revDataDelegate(callback);
        }

        private void netOnline_Init(internetOnlineStatusDelegate online)
        {
            netOnlineStatus = new internetOnlineStatusDelegate(online);
        }
    
        public Client()
        {

        }
        public void client_config(string ip,int pt)
        {
            net_ip = ip;
            net_port = pt;
        }

        private bool is_ip_ads(string str)
        {
            bool ret = false;
            string[] strnum = str.Split('.');
            try
            {
                if (strnum.Length == 4)
                {
                    for (int i = 0; i < strnum.Length; i++)
                    {
                        if (Convert.ToInt32(strnum[i])>-1)
                        {
                            ret = true;
                        }
                    }

                }
            }
            catch(Exception ex)
            {
                return false;
            }
            
            return ret;
        }
        /// <summary>
        /// 连接服务器
        /// </summary>
        /// <returns></returns>
        public bool socket_link()
        {
            try
            {
                IPAddress IP;
                IPHostEntry hosinfo;
                ClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                if(is_ip_ads(net_ip)!=false)
                {
                    IP = IPAddress.Parse(net_ip);
                }
                else
                {
                    hosinfo = Dns.GetHostByName(net_ip);
                    IPAddress[] aryIP = hosinfo.AddressList;
                    IP = aryIP[0];
                }
                ClientSocket.Connect(new IPEndPoint(IP, net_port));
            }
            catch (System.Exception ex)
            {
                ClientSocket.Close();
                return false;
            }
            if (ClientSocket.Connected)
            {
                read = new Thread(ReadThread);
                read.IsBackground = true;
                read.Start();
                netOnlineStatus(true);
            }
            return true;
        }

        public bool socket_send_data(byte [] bdata)
        {
            try
            {
                ClientSocket.Send(bdata);
            }
            catch (System.Exception ex)
            {
                return false;
            }
            return true;
        }
        /// <summary>
        /// 读取线程，用于接收远程机器发来的数据 
        /// </summary>
        private void ReadThread()
        {
            if (ClientSocket != null)
            {
                while (true)
                {
                    byte[] buff = new byte[1024];
                    try
                    {
                        //读取远程机器发来的数据 
                        int size = ClientSocket.Receive(buff);
                        if (size > 0)
                        {
                            byte[] bdat = new byte[size];
                            Array.Copy(buff, 0, bdat, 0, size);
                            revdatadeal(bdat);
                            
                        }
                        else
                        {
                            Thread.Sleep(50);
                        }
                    }
                    catch (Exception e)
                    {
                        if (ClientSocket != null)
                        {
                            ClientSocket.Close();
                            netOnlineStatus(false);
                        }
                        break;
                    }
                    if (ClientSocket.Connected == false)
                    {
                        netOnlineStatus(false);
                    }

                }
            }

        }
        public void socket_close()
        {
            try
            {
                ClientSocket.Shutdown(SocketShutdown.Both);
                ClientSocket.Close();
                ClientSocket.Dispose();
            }
            catch (System.Exception ex)
            {
            }
        }

        public void socket_link_test()
        {
            int Port = 8222;
            IPAddress IP = IPAddress.Parse("127.0.0.1");
            try
            {
                ClientSocket.Connect(new IPEndPoint(IP,Port));
            }
            catch(Exception ex)
            {
                return;
            }

            for(int i=0;i<10;i++)
            {
                try
                {
                    Thread.Sleep(2000);
                    int ReceiveLength = ClientSocket.Receive(result);
                    string sb = Console.ReadLine();
                    string SendMessage = "向服务器发送消息：" + DateTime.Now + "\n" + sb;
                    ClientSocket.Send(Encoding.ASCII.GetBytes(SendMessage));
                }
                catch(Exception ex)
                {
                    ClientSocket.Shutdown(SocketShutdown.Both);
                    ClientSocket.Close();
                }
            }
        }
        #region "网络连接"

        #endregion
    }
}
